package com.grq.framework.redis.config;


import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.data.redis.FastJsonRedisSerializer;
import com.grq.framework.redis.dao.RedisDao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class GrqRedisAutoConfig<T> {

    private Class<T> clazz;

    @Bean
    public RedisTemplate<String, T> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {

        //配置redisTemplate
        RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        FastJsonRedisSerializer<T> fastJsonRedisSerializer = fastJson2RedisSerializer();

        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);

        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    @Bean
    public FastJsonRedisSerializer<T> fastJson2RedisSerializer() {

        FastJsonRedisSerializer<T> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(clazz);

        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
        config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat);

        fastJsonRedisSerializer.setFastJsonConfig(config);

        return fastJsonRedisSerializer;
    }

    @Bean
    public RedisDao redisDao(){
        return new RedisDao();
    }

}
